<!--
 * @Author: your name
 * @Date: 2021-03-11 14:45:37
 * @LastEditTime: 2021-03-12 15:53:00
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \ui-demo\src\components\Login.vue
-->
<template>
  <div class="mainDev">

    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="form">
      <el-form-item label="账号：" prop="username">
        <el-input v-model="ruleForm.username" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input v-model="ruleForm.password" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">登陆</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from '@/api/user.js'
export default {
  // 组件名称
  name: 'Login',
  // 自定义变量
  data () {
    return {
      ruleForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  // 自定义方法
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.ruleForm).then(response => {
            if (response.code === 0) {
              // 登陆后要将返回的token值进行保存到浏览器中，以便后面request.js文件拦截器调用
              localStorage.setItem('access_token', response.data)
              // 登陆后进行跳转到用户首页界面
              this.$router.push({ path: '/user/index' })
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

.mainDev {
    background-color: #fff;
}

.form {
    margin-top: 15%;
    margin-left: 40%;
    width: 500px;
}

</style>
